mini.parse();

function GoodsGroupFormHandler() {
};

GoodsGroupFormHandler.instance = new GoodsGroupFormHandler();

// 获得全局的商品分类表单对象
GoodsGroupFormHandler.goodsGroupForm = new mini.Form("goodsGroupForm");
GoodsGroupFormHandler.formData = {};

// 全局的商品分类编号
GoodsGroupFormHandler.gBggId = null;
// 全局的商品类型属性编号
GoodsGroupFormHandler.gbBgaTattris = null;

// 商品分类状态数据
GoodsGroupFormHandler.bggStateData = [
	{text: "有效",value: 1},
	{text: "无效",value: 0}
];
mini.get("bggState").setData(GoodsGroupFormHandler.bggStateData);

/**
 * 加载商品类型下拉组合框
 * @param {} passingBgtId
 */
GoodsGroupFormHandler.loadGoodsTypeListCob = function(passingBgtId){
	$.ajax({
        url: __root + "/getGoodsTypeListCob.do",
        type: "POST",
        cache: false,
        dataType: 'json',
        success: function (text) {
        	 //设置商品类型数据
        	 if(text != null && text.length > 0) mini.get("bgtCob").setData(text);
        	
        	 //设置默认值
        	 if(passingBgtId != null && passingBgtId.length > 0){
        		mini.get("bgtCob").setValue(passingBgtId);
        	 }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            MiniuiTools.miniError("系统提示", jqXHR.responseText);
        }
    });
}

/**
 * 加载商品类型属性下拉组合框
 * @param {} bgtId
 * @param {} passingBtaIds
 */
GoodsGroupFormHandler.loadGoodsTypeAttrListCob = function(bgtId, passingBtaIds){
	if(bgtId != null && bgtId != "" && bgtId != "undefined"){
		//var gtaUrl = __root + "/getGoodsTypeAttrCob.do?bgtId=" + bgtId;
		//mini.get("bgtAttrCob").setUrl(gtaUrl);
		
		$.ajax({
	        url: __root + "/getGoodsTypeAttrCob.do?bgtId=" + bgtId,
	        cache: false,
	        dataType: 'json',
	        success: function (text) {
	        	//设置类型属性数据
	        	if(text != null && text.length > 0) mini.get("bgtAttrCob").setData(text);
	        	
	        	//设置默认值
	        	if(passingBtaIds != null && passingBtaIds.length > 0) {
					mini.get("bgtAttrCob").setValue(passingBtaIds);	
				}
	        },
	        error: function (jqXHR, textStatus, errorThrown) {
	            MiniuiTools.miniError("系统提示", jqXHR.responseText);
	        }
	    });
	}
}

/**
 * 根据商品类型联动选择商品类型属性
 */
GoodsGroupFormHandler.changeBgtAttrByTypeId = function(){
	var bgtId = mini.get("bgtCob").getValue();
	//清空属性列表组合框
	mini.get("bgtAttrCob").setData(null);
	mini.get("bgtAttrCob").setValue(null);
	
	GoodsGroupFormHandler.loadGoodsTypeAttrListCob(bgtId, null);
}

/**
 * 保存（添加或编辑）商品分类数据的方法
 */
GoodsGroupFormHandler.save = function(){
	var goodsGroupData = GoodsGroupFormHandler.goodsGroupForm.getData();
	goodsGroupData.bggId = GoodsGroupFormHandler.formData.bggId;
	
    GoodsGroupFormHandler.goodsGroupForm.validate();
    if (!GoodsGroupFormHandler.goodsGroupForm.isValid()) return;    
    
    if(mini.get("topBggType").getChecked()) goodsGroupData.bggParent = "0";
    
    var bgtCob = mini.get("bgtCob").getValue();
    var bgtAttrCob = mini.get("bgtAttrCob").getValue();

    if((bgtCob != null && bgtCob != "") && (bgtAttrCob == null || bgtAttrCob == "")){
    	MiniuiTools.miniWarning("系统提示", "商品类型与类型属性需同步配置！");
		return;
	}
	
    var json = mini.encode(goodsGroupData);
    $.ajax({
        url: __root + "/saveOrUpdateGoodsGroup.do",
        type: "POST",
        data: {
        	goodsGroupInfo: json,
        	lslUser: gbOperateUser,
    		lslAddress: gbOperateIp
        },
        cache: false,
        dataType: 'text',
        success: function (bggId) {
        	 if(bggId != null && bggId != ""){
    			GoodsGroupFormHandler.saveOrUpdateBgAttr(bggId, bgtCob, bgtAttrCob);
        	 }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            MiniuiTools.miniError("系统提示", jqXHR.responseText, function(){
            	GoodsGroupFormHandler.closeCurrentWin();
            });
        }
    });
}

/**
 * 保存商品分类属性数据的方法
 * @param {} bggId
 * @param {} bgtId
 * @param {} btaIds
 */
GoodsGroupFormHandler.saveOrUpdateBgAttr = function(bggId, bgtId, btaIds){
	// 新增分类时处理程序
	if(bggId != GoodsGroupFormHandler.gBggId){
		if(btaIds == null || btaIds == ""){
			 MiniuiTools.miniInfo("系统提示","保存成功！", function(action){
        		GoodsGroupFormHandler.closeCurrentWin("save");
        		return;
        	});
		}      
	}
	
	// 编辑分类之前首先判断原有的分类属性是否已被商品使用，如果已经使用，则不能更改，但可以增加新属性。
	if(GoodsGroupFormHandler.baTattriIsUsed(GoodsGroupFormHandler.gbBgaTattris, btaIds)){
		MiniuiTools.miniWarning("系统提示", "当前配置已被商品使用，无法进行撤销操作！");
		return;
	}
	
	// 编辑分类时处理程序
	$.ajax({
        url: __root + "/saveOrUpdateGGAttrInfo.do",
        data: {
        	bggId: bggId, 
        	bgtId: bgtId, 
        	btaIds: btaIds, 
        	gBggId: GoodsGroupFormHandler.gBggId,
        	lslUser: gbOperateUser,
    		lslAddress: gbOperateIp
        },
        cache: false,
        success: function (text) {
        	 MiniuiTools.miniInfo("系统提示","保存成功！", function(action){
        		GoodsGroupFormHandler.closeCurrentWin("save");
        	 	GoodsGroupFormHandler.gBggId = null;
        	});
        },
        error: function (jqXHR, textStatus, errorThrown) {
        	MiniuiTools.miniError("系统提示", jqXHR.responseText, function(){
            	GoodsGroupFormHandler.closeCurrentWin();
           		GoodsGroupFormHandler.gBggId = null;
            });
        }
    });
}

/**
 * 检验类型属性是否被占用
 * @param {} gbBgaTattris
 * @param {} bgaTattris
 * @return {Boolean}
 */
GoodsGroupFormHandler.baTattriIsUsed = function(gbBgaTattris, bgaTattris){
	// 1、编辑之前未配置分类属性则不作判断
	if(gbBgaTattris == null || gbBgaTattris == "") return false;
	
	var strArr = new Array();
	var teStr1 = gbBgaTattris.split(",");
	
	if(bgaTattris == null || bgaTattris == ""){
		for(var i = 0; i < teStr1.length; i++){
			strArr.push("'" + teStr1[i] + "'");
		}
	}else{
		var teStr2 = bgaTattris.split(",");
		
		for(var i = 0; i < teStr1.length; i++){
			var isExists = true;
			
			for(var j = 0; j < teStr2.length; j++){
				if(teStr1[i] == teStr2[j]){
					isExists = true;
					break;
				}
				
				isExists = false;
			}
		
			if(!isExists){
				strArr.push("'" + teStr1[i] + "'");
			}
		}
	}

	// 2、未修改原有属性则不作判断
	if(strArr.length == 0) return false;
	
	// 3、检验是否被占用
	var isUsed = false;
	
	$.ajax({
        url: __root + "/getBgaByBgaTattris.do?bgaTattris="+ strArr.toString(),
        cache: false,
        dataType: 'json',
        async: false,   // 同步执行，默认为true
        success: function (text) {
        	if(text == "0"){
        		isUsed = false; 
        	}else{
        		isUsed = true;
        	}
        },
        error: function (jqXHR, textStatus, errorThrown) {
        	MiniuiTools.miniError("系统提示", jqXHR.responseText, function(){
            	GoodsGroupFormHandler.closeCurrentWin();
            });
        }
    });
	
	return isUsed;
}

/**
 * 根据商品分类编号获得对应的商品分类属性信息
 * 以加载默认配置的分类属性
 * @param {} bgaGgroup
 */
GoodsGroupFormHandler.getBggAttrByBgaGgroup = function(bgaGgroup){
	$.ajax({
        url: __root + "/getBggAttrByBgaGgroup.do?bgaGgroup="+bgaGgroup,
        cache: false,
        dataType: 'json',
        success: function (text) {
        	if(text != null && text.length > 0){
        		var btaIds = "";
        		for(var i = 0; i < text.length - 1; i++){
        			btaIds += text[i].bgaTattri + ","; 
	        	} 
	        	btaIds += text[text.length - 1].bgaTattri;
	        	
	        	//加载商品类型列表，并设定选定的商品类型
        		GoodsGroupFormHandler.loadGoodsTypeListCob(text[0].bgaGtype);
	        	//根据商品类型编号预先加载类型属性列表,并批量设置选定的类型属性列表
        		GoodsGroupFormHandler.loadGoodsTypeAttrListCob(text[0].bgaGtype, btaIds);
        		
        		GoodsGroupFormHandler.gbBgaTattris = btaIds;
        	}else{
        		//如果没有配置属性，则设置默认值
        		GoodsGroupFormHandler.loadGoodsTypeListCob(null);
        	}
        },
        error: function (jqXHR, textStatus, errorThrown) {
        	MiniuiTools.miniError("系统提示", jqXHR.responseText, function(){
            	GoodsGroupFormHandler.closeCurrentWin();
            });
        }
    });
}

/**
 * 读取并选中默认父亲节点
 * @param {} bagParent
 */
GoodsGroupFormHandler.getParentBggInfo = function(bggParent){
    $.ajax({ 
        url: __root + "/getGoodsGroupInfoById.do?bggId=" + bggParent,
        cache: false,
        dataType: 'json',
        success: function (parentText) {
        	//动态加载节点时，需同时设置setValue，setText，且必须先setValue，然后再setText
        	if(parentText == null || parentText == "" || parentText.bggId == null 
        		|| parentText.bggId == "undefined"
        		|| parentText.bggId == "0"){
        		mini.get("bggParentTree").setEnabled(false);
				mini.get("topBggType").setChecked(true);
        	}else{
        		mini.get("bggParentTree").setValue(parentText.bggId);
	            mini.get("bggParentTree").setText(parentText.bggName);
        	}
        }
    });
}

/**
 * 标准方法接口定义
 * @param {} data
 */
GoodsGroupFormHandler.passData = function(data) {
    if (data.action == "edit") {
        //跨页面传递的数据对象，克隆后才可以安全使用
        data = mini.clone(data);
        GoodsGroupFormHandler.formData.bggId = data.bggId;
        
        //根据id获取对应的商品分类信息
        $.ajax({ 
            url: __root + "/getGoodsGroupInfoById.do?bggId=" + data.bggId,
            cache: false,
            dataType: 'json',
            success: function (text) {
                GoodsGroupFormHandler.goodsGroupForm.setData(text);
                GoodsGroupFormHandler.getParentBggInfo(text.bggParent);
            }
        });
        
        GoodsGroupFormHandler.gBggId = data.bggId;
    	GoodsGroupFormHandler.getBggAttrByBgaGgroup(data.bggId);
        
    }else{
    	if(data.bggId != null && data.bggId != "0"){
    		//新增商品分类时，选定默认父节点
			mini.get("bggParentTree").setValue(data.bggId);
            mini.get("bggParentTree").setText(data.bggName);
    	}else{
    		//如果没有选中数据，就默认父亲节点为顶级节点
    		mini.get("bggParentTree").setEnabled(false);
    		mini.get("topBggType").setChecked(true);
    	}
    	
    	GoodsGroupFormHandler.loadGoodsTypeListCob(null);
    	//默认商品分类状态为有效
    	mini.get("bggState").setValue(1);
    }
}

/**
 * 顶级分类mini-checkbox选择改变事件
 * @param {} e
 */
GoodsGroupFormHandler.selectedTopBggType = function(e){
	var isChecked = this.getChecked();
 	if(isChecked){
 		mini.get("bggParentTree").setEnabled(false);
 	}else{
 		mini.get("bggParentTree").setEnabled(true);
 	}
}

/**
 * 关闭窗口
 * @param {} action
 */
GoodsGroupFormHandler.closeCurrentWin = function(action) {
    if (window.CloseOwnerWindow) window.CloseOwnerWindow(action);
    else window.close();
}

GoodsGroupFormHandler.closeMiniWin = function(){
	GoodsGroupFormHandler.closeCurrentWin("cancel");
}